﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EAILogWebSite.Models;
using System.Web.Routing;
using System.Xml;

namespace EAILogWebSite.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        public ActionResult Index(int? pn, int? lid, string msgid, string corrid, int? ishistory, int? msgtype,
            string startdate, string enddate, string msgcontent, string SenderID, string ReceiverID, string srvopname)
        {
            RouteValueDictionary rvd = new RouteValueDictionary();
            QueryParaModels qpm = new QueryParaModels();

            //Create search
            var dbContext = new EAIDBEntities();

            IQueryable<LogEntity> result;
            result = CreateQuery(ishistory, rvd, dbContext);

            int currentPage = 1;
            if (pn.HasValue)
                currentPage = pn.Value;

            //set id query condition
            if (lid.HasValue)
            {
                result = result.Where(x => x.Id == lid);
                rvd.Add("lid", lid.Value);
            }

            if (!string.IsNullOrEmpty(msgid))
            {
                result = result.Where(x => x.MsgID == msgid);
                rvd.Add("msgid", msgid);
            }

            if (!string.IsNullOrEmpty(corrid))
            {
                result = result.Where(x => x.CorrID == corrid);
                rvd.Add("corrid", corrid);
            }

            if (msgtype.HasValue)
            {
                if (msgtype.Value == 1) { result = result.Where(x => x.MsgType == "Request"); }
                if (msgtype.Value == 2) { result = result.Where(x => x.MsgType == "Response"); }
                rvd.Add("msgtype", msgtype);
            }

            if (!string.IsNullOrEmpty(SenderID) && SenderID != "Any")
            {
                result = result.Where(x => x.SenderID == SenderID || x.ReceiverID == SenderID);
                rvd.Add("SenderID", SenderID);
            }

            if (!string.IsNullOrEmpty(ReceiverID) && ReceiverID != "Any")
            {
                result = result.Where(x => x.ReceiverID == ReceiverID || x.SenderID == ReceiverID);
                rvd.Add("ReceiverID", ReceiverID);
            }

            if (!string.IsNullOrEmpty(srvopname))
            {
                result = result.Where(x => x.SrvOpName == srvopname);
                rvd.Add("srvopname", srvopname);
            }

            DateTime tmpStartDate = DateTime.Now;
            if (!string.IsNullOrEmpty(startdate))
            {
                if (DateTime.TryParse(startdate, out tmpStartDate))
                {
                    result = result.Where(x => x.LogDateTime >= tmpStartDate);
                    rvd.Add("startdate", startdate);
                }
                else
                {
                    ModelState.AddModelError("StartDate", "The StartTime formate is error. This should be '2010/01/01 01:01:01'.");
                }
            }

            DateTime tmpEndDate = DateTime.Now;
            if (!string.IsNullOrEmpty(enddate))
            {
                if (DateTime.TryParse(enddate, out tmpEndDate))
                {
                    tmpEndDate = tmpEndDate.AddSeconds(1);
                    result = result.Where(x => x.LogDateTime <= tmpEndDate);
                    rvd.Add("enddate", enddate);
                }
                else
                {
                    ModelState.AddModelError("EndDate", "The EndTime formate is error. This should be '2010/01/01 01:01:01'.");
                }
            }

            if (!string.IsNullOrEmpty(msgcontent))
            {
                //must set startdate and enddate
                if (string.IsNullOrEmpty(enddate) || string.IsNullOrEmpty(startdate))
                {
                    ModelState.AddModelError("MsgContent", "The content query will spend most time, please set the startdate and enddate.");
                }
                //timespan between startdate and enddate can't larger than 1 day.
                else if ((tmpEndDate - tmpStartDate) >= TimeSpan.FromHours(25))
                {
                    ModelState.AddModelError("MsgContent", "The content query will spend most time, and the timespan between startdate and enddate can't larger than 1 day.");
                }
                else
                {
                    result = result.Where(x => x.MsgBody.Contains(msgcontent));
                }

                rvd.Add("msgcontent", msgcontent);
            }

            if (ModelState.IsValid)
            {
                //start search
                ViewData["RVD"] = rvd;
                ViewData["TotalPage"] = (result.Count() - 1) / 40 + 1;
                ViewData["CurrentPage"] = currentPage;
                ViewData["QueryResult"] = result.Skip(((currentPage - 1) * 40)).Take(40);
            }

            CreateSenderAndReceiverViewData();

            return View();
        }

        private void CreateSenderAndReceiverViewData()
        {
            ViewData["SenderLists"] = new List<SelectListItem>()
                {
                        new SelectListItem() {Text="Any", Value="Any", Selected=true},
                        new SelectListItem() {Text="AURA", Value="AURA"},
                        new SelectListItem() {Text="B2B", Value="B2B"},
                        new SelectListItem() {Text="CCS", Value="CCS"},
                        new SelectListItem() {Text="EBS", Value="EBS"},
                        new SelectListItem() {Text="iCare", Value="iCare"},
                        new SelectListItem() {Text="LA", Value="LA"},
                        new SelectListItem() {Text="MAP", Value="MAP"},
                        new SelectListItem() {Text="MEDS", Value="MEDS"},
                        new SelectListItem() {Text="MTS", Value="MTS"},
                        new SelectListItem() {Text="PASS", Value="PASS"},
                        new SelectListItem() {Text="WTS", Value="WTS"},
                };
            ViewData["ReceiverLists"] = new List<SelectListItem>()
                {
                        new SelectListItem() {Text="Any", Value="Any", Selected=true},
                        new SelectListItem() {Text="AURA", Value="AURA"},
                        new SelectListItem() {Text="B2B", Value="B2B"},
                        new SelectListItem() {Text="CCS", Value="CCS"},
                        new SelectListItem() {Text="EBS", Value="EBS"},
                        new SelectListItem() {Text="iCare", Value="iCare"},
                        new SelectListItem() {Text="LA", Value="LA"},
                        new SelectListItem() {Text="MAP", Value="MAP"},
                        new SelectListItem() {Text="MEDS", Value="MEDS"},
                        new SelectListItem() {Text="MTS", Value="MTS"},
                        new SelectListItem() {Text="PASS", Value="PASS"},
                        new SelectListItem() {Text="WTS", Value="WTS"},
                };
        }

        private void CrateSrvOpNameViewData()
        {
            ViewData["SrvOpName"] = new List<SelectListItem>()
                {
                        new SelectListItem() {Text="Any", Value="Any", Selected=true},
                        new SelectListItem() {Text="applyContractUpdateservice", Value="applyContractUpdateservice"},
                        new SelectListItem() {Text="AuraService", Value="AuraService"},
                        new SelectListItem() {Text="BRWVALservice", Value="BRWVALservice"},
                        new SelectListItem() {Text="calPremiumservice", Value="calPremiumservice"},
                        new SelectListItem() {Text="CLIRSKservice", Value="CLIRSKservice"},
                        new SelectListItem() {Text="createProposalservice", Value="createProposalservice"},
                        new SelectListItem() {Text="EBScreateProposal", Value="EBScreateProposal"},
                        new SelectListItem() {Text="ICBCFreeValiservice", Value="ICBCFreeValiservice"},
                        new SelectListItem() {Text="ICBCMantValiservice", Value="ICBCMantValiservice"},
                        new SelectListItem() {Text="ICBCSurrValiservice", Value="ICBCSurrValiservice"},
                        new SelectListItem() {Text="inquiryInsPolHistservice", Value="inquiryInsPolHistservice"},
                        new SelectListItem() {Text="POLENQservice", Value="POLENQservice"},
                        new SelectListItem() {Text="POSPRCservice", Value="POSPRCservice"},
                        new SelectListItem() {Text="posregservice", Value="posregservice"},
                        new SelectListItem() {Text="updateClientInfservice", Value="updateClientInfservice"},
                        new SelectListItem() {Text="updateDispatchAddservice", Value="updateDispatchAddservice"},
                        new SelectListItem() {Text="valClientservice", Value="valClientservice"},
                        new SelectListItem() {Text="EBSLogin", Value="EBSLogin"},
                        new SelectListItem() {Text="StateUpdate", Value="StateUpdate"},
                        new SelectListItem() {Text="SaveRiskassess", Value="SaveRiskassess"},
                        new SelectListItem() {Text="GetExistCustomers", Value="GetExistCustomers"},
                        new SelectListItem() {Text="GetSalesInfos", Value="GetSalesInfos"},
                        new SelectListItem() {Text="GetEBAppInsuerds", Value="GetEBAppInsuerds"},
                        new SelectListItem() {Text="GetEBAppProdInfo", Value="GetEBAppProdInfo"},
                        new SelectListItem() {Text="GetEBClaimInfoList", Value="GetEBClaimInfoList"},
                        new SelectListItem() {Text="GetEBApplicationList", Value="GetEBApplicationList"},
                        new SelectListItem() {Text="MobileSalesService", Value="MobileSalesService"},
                        new SelectListItem() {Text="AgentComQuery", Value="AgentComQuery"},
                };
        }

        private static IQueryable<LogEntity> CreateQuery(int? ishistory, RouteValueDictionary rvd, EAIDBEntities dbContext)
        {
            IQueryable<LogEntity> result;
            if (ishistory.HasValue && ishistory.Value == 1)
            {
                rvd.Add("ishistory", 1);
                result = dbContext.Table_Log_bak.Select(x => new LogEntity
                {
                    Id = x.Id,
                    MsgID = x.MsgID,
                    LogDateTime = x.LogDateTime,
                    MsgType = x.MsgType,
                    SenderID = x.SenderID,
                    ReceiverID = x.ReceiverID,
                    SrvOpName = x.SrvOpName,
                    CorrID = x.CorrID,
                    ESBRspCode = x.ESBRspCode,
                    MsgBody = x.MsgBody,
                });
            }
            else
            {
                rvd.Add("ishistory", 0);
                result = dbContext.Table_Log.Select(x => new LogEntity
                {
                    Id = x.Id,
                    MsgID = x.MsgID,
                    LogDateTime = x.LogDateTime,
                    MsgType = x.MsgType,
                    SenderID = x.SenderID,
                    ReceiverID = x.ReceiverID,
                    SrvOpName = x.SrvOpName,
                    CorrID = x.CorrID,
                    ESBRspCode = x.ESBRspCode,
                    MsgBody = x.MsgBody,
                });
            }

            result = result.OrderByDescending(x => x.Id);

            return result;
        }

        [HttpPost]
        public ActionResult Index(QueryParaModels model)
        {
            System.Web.Routing.RouteData routData = new System.Web.Routing.RouteData();

            if (model.Lid.HasValue)
            {
                routData.Values.Add("lid", model.Lid);
            }

            if (!string.IsNullOrEmpty(model.MsgId))
            {
                routData.Values.Add("msgid", model.MsgId.Trim());
            }

            if (!string.IsNullOrEmpty(model.CorrId))
            {
                routData.Values.Add("corrid", model.CorrId.Trim());
            }

            if (!string.IsNullOrEmpty(model.SrvOpName))
            {
                routData.Values.Add("srvopname", model.SrvOpName.Trim());
            }


            if (model.IsHistory.HasValue)
            {
                routData.Values.Add("ishistory", model.IsHistory.Value);
            }

            if (model.MsgType.HasValue)
            {
                routData.Values.Add("msgtype", model.MsgType.Value);
            }



            routData.Values.Add("startdate", model.StartDate);
            routData.Values.Add("enddate", model.EndDate);
            routData.Values.Add("msgcontent", model.MsgContent);
            routData.Values.Add("SenderID", model.SenderID);
            routData.Values.Add("ReceiverID", model.ReceiverID);

            return RedirectToAction("Index", "Home", routData.Values);
        }



        public ActionResult Detail(int id)
        {
            var dbContext = new EAIDBEntities();

            var log = dbContext.Table_Log.FirstOrDefault(x => x.Id == id);

            if (log == null)
            {
                var log_bak = dbContext.Table_Log_bak.FirstOrDefault(x => x.Id == id);
                return View(log_bak);
            }
            else
            {
                return View(log);
            }

        }

        public ActionResult Test()
        {
            return View();
        }

        /// <summary>
        /// export a excel
        /// </summary>
        /// <returns></returns>
        public ActionResult export(string date)
        {
            var dbContext = new EAIDBEntities();
            string dateStr = DateTime.Parse(date).ToString("yyyy-MM-dd");

            IQueryable<LogEntity> result;
            result = dbContext.Table_Log.Where(x => x.SrvDate == dateStr).Select(x => new LogEntity
                {
                    Id = x.Id,
                    MsgID = x.MsgID,
                    LogDateTime = x.LogDateTime,
                    MsgType = x.MsgType,
                    SenderID = x.SenderID,
                    ReceiverID = x.ReceiverID,
                    SrvOpName = x.SrvOpName,
                    CorrID = x.CorrID,
                    ESBRspCode = x.ESBRspCode,
                    Field5 = x.ResField5,
                });

            if (result.Count() == 0)
            {
                result = dbContext.Table_Log_bak.Where(x => x.SrvDate == dateStr).Select(x => new LogEntity
                {
                    Id = x.Id,
                    MsgID = x.MsgID,
                    LogDateTime = x.LogDateTime,
                    MsgType = x.MsgType,
                    SenderID = x.SenderID,
                    ReceiverID = x.ReceiverID,
                    SrvOpName = x.SrvOpName,
                    CorrID = x.CorrID,
                    ESBRspCode = x.ESBRspCode,
                    Field5 = x.ResField5,
                });
            }

            Response.AddHeader("Content-Typle", "application/msexcel");
            //Response.AddHeader(""
            return View(result);
        }

        /// <summary>
        /// Fress Test
        /// </summary>
        /// <returns></returns>
        public ActionResult FreeTest()
        {
            CreateSenderAndReceiverViewData();
            CrateSrvOpNameViewData();
            return View();
        }

        //[HttpPost]
        ////public ActionResult FreeTest(LogEntity logEntity)
        //{
        //    XmlDocument xmldoc = new XmlDocument();
        //    xmldoc.LoadXml(logEntity.MsgBody);
        //    XmlElement element = (XmlElement)xmldoc.FirstChild;

        //    ESBEnvelope envelope = new ESBEnvelope()
        //    {
        //        ESBHeader = new ESBEnvelopeESBHeader()
        //        {
        //            ReceiverID = "AURA",
        //            SrvOpName = "underwrite",
        //            SenderID = "Dox"
        //        },

        //        MsgBody = element,
        //    };
        //    EAIWebService.
        //    ESBWebEntrySoapClient client = new ESBWebEntrySoapClient();

        //    var result = client.ProcessMessage(envelope);
        //    return View();
        //}
    }
}
